package org.springbus.habit.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springbus.habit.entity.*;
import org.springbus.habit.service.*;
import org.springbus.habit.web.entity.*;
import org.springbus.habit.web.request.SkuInfoRequest;
import org.springbus.habit.web.response.CommonResponse;
import org.springbus.habit.web.response.PageResponse;
import org.springbus.habit.web.response.SkuResponse;
import org.springbus.habit.web.response.SpuResponse;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * spu 前端控制器
 * </p>
 *
 * @author Mr.Han
 * @since 2024-05-16
 */
@Tag(name = "客户需求管理")
@RestController
public class SpuController {

    @Resource
    private SpuService spuService;

    @Resource
    private SkuService skuService;

    @Resource
    private SpuImageService spuImageService;

    @Resource
    private SpuSaleService spuSaleService;

    @Resource
    private SpuSaleValueService spuSaleValueService;

    @Resource
    private AttributeInfoService attributeInfoService;

    @Resource
    private LabelService labelService;


    @GetMapping("/admin/product/attrInfoList/{page}/{limit}")
    @Operation(summary = "分页查询spu列表")
    public PageResponse<SpuResponse> getPageList(
            @Parameter(description = "当前页码", required = true) @PathVariable Long page,
            @Parameter(description = "每页条数", required = true) @PathVariable Long limit,
            @Parameter(description = "三级菜单ID", required = true) Long category3Id) {

        Page<Spu> pageInfo = spuService.page(new Page<>(page, limit), new QueryWrapper<Spu>().eq("category_id", category3Id)
                .eq("deleted", false));
        if (Objects.isNull(pageInfo) || CollectionUtils.isEmpty(pageInfo.getRecords())) {
            return new PageResponse<>(Lists.newArrayList(), 0L);
        }
        List<SpuResponse> list = pageInfo.getRecords().stream()
                .map(spu -> new SpuResponse().setCategory3Id(category3Id)
                        .setDescription(spu.getDescription())
                        .setId(spu.getId())
                        .setSpuName(spu.getName())
                        .setTmId(spu.getTmId())
                ).toList();
        return new PageResponse<>(list, pageInfo.getTotal());
    }

    @PostMapping("/admin/product/saveSpuInfo")
    @Operation(summary = "保存/修改 spu信息")
    public CommonResponse<Boolean> saveOrUpdateSpuInfo(@RequestBody SpuResponse request) {

        Spu spu = new Spu().setCategoryId(request.getCategory3Id())
                .setTmId(request.getTmId())
                .setDescription(request.getDescription())
                .setName(request.getSpuName())
                .setDeleted(false)
                .setGmtCreate(new Date());
        spuService.saveOrUpdate(spu);

        List<SpuImageEntity> spuImageList = request.getSpuImageList();
        List<SpuImage> imgList = Optional.ofNullable(spuImageList).orElse(Lists.newArrayList()).stream()
                .map(e -> new SpuImage().setSpuId(spu.getId())
                        .setImgUrl(e.getImgUrl())
                        .setName(e.getImgName())
                        .setDeleted(false)
                        .setGmtCreate(new Date())).toList();
        spuImageService.saveOrUpdateBatch(imgList);

        List<SpuSaleAttrList> spuSaleAttrList = request.getSpuSaleAttrList();
        List<SpuSale> saleList = Lists.newArrayList();
        List<SpuSaleValue> spuSaleValues = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(spuSaleAttrList)) {
            spuSaleAttrList.forEach(attr -> {
                SpuSale spuSale = new SpuSale()
                        .setSpuId(spu.getId())
                        .setSaleAttrId(Long.valueOf(attr.getBaseSaleAttrId()))
                        .setName(attr.getSaleAttrName())
                        .setDeleted(false)
                        .setGmtCreate(new Date());

                saleList.add(spuSale);
                attr.getSpuSaleAttrValueList().forEach(v -> {
                    SpuSaleValue spuSaleValue = new SpuSaleValue()
                            .setSaleAttrId(Long.valueOf(attr.getBaseSaleAttrId()))
                            .setValue(v.getSaleAttrValueName())
                            .setIsChecked(false)
                            .setDeleted(false)
                            .setGmtCreate(new Date());
                    spuSaleValues.add(spuSaleValue);

                });
            });
        }
        spuSaleService.saveOrUpdateBatch(saleList);
        spuSaleValueService.saveOrUpdateBatch(spuSaleValues);
        return new CommonResponse<>(true);
    }

    @GetMapping("/admin/product/spuImageList/{spuId}")
    @Operation(summary = "查询spu图片列表")
    public CommonResponse<List<SpuImageEntity>> getSpuImageList(@Parameter(description = "spu Id", required = true) @PathVariable Long spuId) {
        List<SpuImageEntity> list = spuImageService.list(new QueryWrapper<SpuImage>().eq("spu_id", spuId)
                .eq("deleted", false)).stream().map(e -> new SpuImageEntity().setImgName(e.getName())
                .setImgUrl(e.getImgUrl()).setSpuId(spuId).setId(e.getId())).toList();
        return new CommonResponse<>(list);
    }

    @GetMapping("/admin/product/getSpuById/{id}")
    @Operation(summary = "根据spu ID查询spu信息")
    public CommonResponse<SpuResponse> getSpuById(@Parameter(description = "spu ID", required = true) @PathVariable Long id) {
        Spu spu = spuService.getOne(new QueryWrapper<Spu>().eq("id", id)
                .eq("deleted", false));
        if (Objects.isNull(spu)) {
            return new CommonResponse<>(new SpuResponse());
        }

        List<SpuSale> list = spuSaleService.list(new QueryWrapper<SpuSale>().eq("spu_id", spu.getId())
                .eq("deleted", false));
        List<SpuSaleAttrList> spuSaleAttrList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SpuSale spuSale : list) {
                Long saleAttrId = spuSale.getSaleAttrId();
                List<SpuSaleValue> spuSaleValues = spuSaleValueService.list(new QueryWrapper<SpuSaleValue>()
                        .eq("sale_attr_id", saleAttrId).eq("deleted", false));

                List<SpuSaleAttrValueList> valueLists = Optional.ofNullable(spuSaleValues).orElse(Lists.newArrayList()).stream()
                        .map(e -> new SpuSaleAttrValueList().setBaseSaleAttrId(String.valueOf(e.getSaleAttrId()))
                                .setSaleAttrValueName(e.getValue()).setId(e.getId()).setSaleAttrName(spuSale.getName())
                                .setSpuId(spu.getId())).toList();
                SpuSaleAttrList attrList = new SpuSaleAttrList()
                        .setId(spuSale.getId())
                        .setSpuId(spuSale.getSpuId())
                        .setBaseSaleAttrId(String.valueOf(saleAttrId))
                        .setSaleAttrName(spuSale.getName())
                        .setSpuSaleAttrValueList(valueLists);
                spuSaleAttrList.add(attrList);
            }
        }
        SpuResponse spuResponse = new SpuResponse().setCategory3Id(spu.getCategoryId())
                .setDescription(spu.getDescription())
                .setId(spu.getId())
                .setSpuName(spu.getName())
                .setTmId(spu.getTmId())
                .setSpuImageList(Lists.newArrayList())
                .setSpuSaleAttrList(spuSaleAttrList);
        return new CommonResponse<>(spuResponse);
    }

    @DeleteMapping("/admin/product/deleteSpu/{id}")
    @Operation(summary = "删除spu")
    public CommonResponse<Boolean> removeSpu(@Parameter(description = "spu ID", required = true) @PathVariable Long id) {
        List<SpuSale> list = spuSaleService.list(new QueryWrapper<SpuSale>().eq("spu_id", id)
                .eq("deleted", false));
        if (CollectionUtils.isNotEmpty(list)) {
            for (SpuSale spuSale : list) {
                spuSaleValueService.update(new SpuSaleValue().setIsChecked(false).setDeleted(true).setGmtModified(new Date())
                        , new QueryWrapper<SpuSaleValue>().eq("sale_attr_id", spuSale.getSaleAttrId())
                                .eq("deleted", false));


            }
        }
        spuSaleService.update(new SpuSale().setDeleted(true).setGmtModified(new Date())
                , new QueryWrapper<SpuSale>().eq("spu_id", id)
                        .eq("deleted", false));
        spuImageService.update(new SpuImage().setDeleted(true).setGmtModified(new Date())
                , new QueryWrapper<SpuImage>().eq("spu_id", id).eq("deleted", false));
        spuService.update(new Spu().setDeleted(true).setGmtModified(new Date()), new QueryWrapper<Spu>()
                .eq("id", id));
        return new CommonResponse<>(true);
    }

    @GetMapping("/admin/product/spuSaleAttrList/{spuId}")
    @Operation(summary = "查询spu销售属性列表")
    public CommonResponse<List<SpuSaleAttrList>> getSpuSaleAttrList(
            @Parameter(description = "spu ID", required = true) @PathVariable Long spuId) {
        List<SpuSale> list = spuSaleService.list(new QueryWrapper<SpuSale>().eq("spu_id", spuId)
                .eq("deleted", false));
        List<SpuSaleAttrList> lists = list.stream().map(e -> {
            List<SpuSaleValue> spuSaleValues = spuSaleValueService.list(new QueryWrapper<SpuSaleValue>().eq("sale_attr_id", e.getSaleAttrId()));
            List<SpuSaleAttrValueList> valueLists = spuSaleValues.stream().map(v -> new SpuSaleAttrValueList().setId(v.getId())
                    .setBaseSaleAttrId(String.valueOf(v.getSaleAttrId()))
                    .setSaleAttrName(e.getName())
                    .setSaleAttrValueName(v.getValue())
                    .setSpuId(e.getSpuId())
                    .setIsChecked(v.getIsChecked())).toList();
            return new SpuSaleAttrList().setId(e.getId())
                    .setSpuId(e.getSpuId())
                    .setBaseSaleAttrId(String.valueOf(e.getSaleAttrId()))
                    .setSaleAttrName(e.getName())
                    .setSpuSaleAttrValueList(valueLists);
        }).toList();
        return new CommonResponse<>(lists);
    }

    @PostMapping("/admin/product/saveSkuInfo")
    @Operation(summary = "保存sku信息")
    public CommonResponse<Boolean> saveSkuInfo(@RequestBody SkuInfoRequest request) {
        Sku sku = new Sku();
        sku.setCategoryId(request.getCategory3Id());
        sku.setSpuId(request.getSpuId());
        sku.setDescription(request.getSkuDesc());
        sku.setSkuDefaultImg(request.getSkuDefaultImg());
        sku.setWeight(request.getWeight());
        sku.setPrice(request.getPrice());
        sku.setName(request.getSkuName());
        sku.setDeleted(false);
        sku.setGmtCreate(new Date());
        skuService.save(sku);

        List<SkuAttrValueList> skuAttrValueList = request.getSkuAttrValueList();
        List<SkuSaleAttrValueList> skuSaleAttrValueList = request.getSkuSaleAttrValueList();
        if (CollectionUtils.isNotEmpty(skuAttrValueList)) {
            skuAttrValueList.forEach(e -> labelService.update(new Label().setIsChecked(true).setGmtModified(new Date())
                    , new QueryWrapper<Label>().eq("id", e.getValueId())));
        }
        if (CollectionUtils.isNotEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.forEach(e -> {
                spuSaleValueService.update(new SpuSaleValue().setIsChecked(true).setGmtModified(new Date())
                        , new QueryWrapper<SpuSaleValue>().eq("id", e.getSaleAttrValueId())
                                .eq("sale_attr_id", e.getSaleAttrId()));
            });
        }
        return new CommonResponse<>(true);
    }

    @GetMapping("/admin/product/findBySpuId/{id}")
    @Operation(summary = "根据spu ID查询sku信息")
    public CommonResponse<List<SkuResponse>> getSkuList(@Parameter(description = "spu ID", required = true) @PathVariable Long id) {
        List<Sku> list = skuService.list(new QueryWrapper<Sku>().eq("spu_id", id)
                .eq("deleted", false));
        List<SkuResponse> skuResponses = list.stream().map(e -> new SkuResponse().setCategory3Id(e.getCategoryId())
                .setPrice(e.getPrice())
                .setSkuDefaultImg(e.getSkuDefaultImg())
                .setSkuDesc(e.getDescription())
                .setSkuName(e.getName())
                .setSpuId(e.getSpuId())
                .setWeight(e.getWeight())
                .setCreateTime(e.getGmtCreate())
                .setId(e.getId())).toList();
        return new CommonResponse<>(skuResponses);
    }
}
